
<template>  
  <div class="category-management">  
    <!-- 搜索和操作区域 -->  
    <el-card class="box-card operation-container" shadow="never">  
      <el-row type="flex" justify="space-between" align="middle">  
        <el-col :span="20">  
          <el-form :inline="true" :model="searchForm" class="demo-form-inline">  
            <el-form-item label="类别名称">  
              <el-input 
                v-model="searchForm.name" 
                placeholder="输入类别名称"
                clearable
                @clear="handleReset"
                @keyup.enter="onSearch">
              </el-input>  
            </el-form-item>  
            <el-form-item>  
              <el-button type="primary" @click="onSearch" :loading="searchLoading">  
                查询  
              </el-button>  
            </el-form-item>  
          </el-form>  
        </el-col>  
        <el-col :span="4" style="text-align: right;">  
          <el-button type="warning" @click="addCategory">  
            <el-icon><Plus /></el-icon> 添加类别  
          </el-button>  
        </el-col>  
      </el-row>  
    </el-card>  

    <!-- 表格区域 -->  
    <el-card class="box-card table-container" shadow="never">  
      <el-table :data="filteredTableData" style="width: 100%" border v-loading="loading">  
        <el-table-column prop="categoryId" label="ID" width="120" align="center" />  
        <el-table-column prop="categoryName" label="类别名称" align="center">  
          <template #default="scope">  
            {{ scope.row.categoryName }}
          </template>  
        </el-table-column>  
        <el-table-column prop="createTime" label="创建时间" width="180" align="center" />  
        <el-table-column prop="updateTime" label="更新时间" width="180" align="center" />  
        <el-table-column label="操作" width="200" align="center">  
          <template #default="scope">  
            <el-button 
              type="primary" 
              size="small" 
              :icon="Edit" 
              @click="handleEdit(scope.row)">  
              编辑  
            </el-button>
            <el-button 
              type="warning" 
              size="small" 
              :icon="Delete" 
              @click="handleDelete(scope.row)">  
              删除  
            </el-button>  
          </template>  
        </el-table-column>  
      </el-table>  
      
      <!-- 分页区域 -->  
      <div class="pagination-container">  
        <span>第{{ currentPage }}页/共{{ total }}条记录</span>  
        <el-pagination  
          background  
          layout="prev, pager, next"  
          :total="total"
          :page-size="pageSize"
          v-model:current-page="currentPage"
          @current-change="handlePageChange"
          class="ml-auto"  
        />  
      </div>  
    </el-card>

    <!-- 编辑分类弹窗 -->
    <el-dialog 
      v-model="editDialogVisible" 
      title="编辑分类" 
      width="500px" 
      @close="resetEditForm">
      
      <el-form 
        :model="editForm" 
        :rules="editFormRules" 
        ref="editFormRef" 
        label-width="100px">
        
        <el-form-item label="分类名称" prop="categoryName">
          <el-input
            v-model="editForm.categoryName"
            placeholder="请输入分类名称"
            clearable
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button 
            type="primary" 
            @click="submitEditForm" 
            :loading="editSubmitLoading">
            更新
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>  
</template>  

<script setup>  
import { ref, reactive, onMounted, computed } from 'vue';  
import { ElMessage, ElMessageBox } from 'element-plus';  
import { Search, Plus, Delete, Edit } from '@element-plus/icons-vue';  
import request from '../../util/request.js'

// 响应式状态
const loading = ref(false)
const searchLoading = ref(false)
const editSubmitLoading = ref(false)

// 搜索表单数据  
const searchForm = ref({  
  name: ''  
});  

// 表格数据
const tableData = ref([]);
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)

// 编辑相关
const editDialogVisible = ref(false)
const editFormRef = ref(null)
const editForm = reactive({
  categoryId: null,
  categoryName: ''
})

const editFormRules = reactive({
  categoryName: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
    { min: 2, max: 50, message: '分类名称长度在 2 到 50 个字符', trigger: 'blur' }
  ]
})

// 过滤后的表格数据（用于搜索）
const filteredTableData = computed(() => {
  if (!searchForm.value.name) {
    return tableData.value
  }
  return tableData.value.filter(item => 
    item.categoryName.toLowerCase().includes(searchForm.value.name.toLowerCase())
  )
})

// 获取分类列表
const fetchCategoryList = async () => {
  loading.value = true
  try {
    const response = await request.get('/admin/categories/list')
    console.log('分类列表响应:', response)
    
    if (response.data && response.data.code === 1) {
      tableData.value = response.data.data || []
      total.value = tableData.value.length
    } else {
      ElMessage.error(response.data?.msg || '数据加载失败')
    }
  } catch (error) {
    console.error('获取分类列表时出错:', error)
    ElMessage.error('网络连接失败或服务器错误')
  } finally {
    loading.value = false
  }
}

// 搜索功能
const onSearch = () => {
  searchLoading.value = true
  setTimeout(() => {
    const keyword = searchForm.value.name || '全部'
    ElMessage.info(`正在搜索: ${keyword}`)
    searchLoading.value = false
  }, 500)
}

// 重置搜索
const handleReset = () => {
  searchForm.value.name = ''
}

// 分页处理
const handlePageChange = (page) => {
  currentPage.value = page
  // 如果需要服务端分页，可以在这里调用API
}

// 添加类别
const addCategory = () => {  
  ElMessageBox.prompt('请输入新的类别名称', '添加类别', {  
    confirmButtonText: '确定',  
    cancelButtonText: '取消',  
    inputPattern: /^.{2,50}$/,  
    inputErrorMessage: '类别名称长度在2-50个字符之间',  
  })  
    .then(async ({ value }) => {  
      try {
        const response = await request.post('/admin/categories/add', {
          categoryName: value
        })
        
        if (response.data && response.data.code === 1) {
          ElMessage.success(`添加类别 "${value}" 成功`)
          await fetchCategoryList() // 重新获取数据
        } else {
          ElMessage.error(response.data?.msg || '添加失败')
        }
      } catch (error) {
        console.error('添加分类失败:', error)
        ElMessage.error('网络错误，添加失败')
      }
    })  
    .catch(() => {  
      ElMessage.info('已取消添加')
    })
}

// 编辑分类
const handleEdit = (row) => {
  editDialogVisible.value = true
  editForm.categoryId = row.categoryId
  editForm.categoryName = row.categoryName
}

// 提交编辑表单
const submitEditForm = () => {
  if (!editFormRef.value) return
  
  editFormRef.value.validate(async (valid) => {
    if (valid) {
      editSubmitLoading.value = true
      try {
        const response = await request.put('/admin/categories/update', editForm)
        
        if (response.data && response.data.code === 1) {
          ElMessage.success('分类更新成功')
          editDialogVisible.value = false
          await fetchCategoryList() // 重新获取数据
        } else {
          ElMessage.error(response.data?.msg || '更新失败')
        }
      } catch (error) {
        console.error('更新分类失败:', error)
        ElMessage.error('网络错误，更新失败')
      } finally {
        editSubmitLoading.value = false
      }
    }
  })
}

// 重置编辑表单
const resetEditForm = () => {
  if (editFormRef.value) {
    editFormRef.value.resetFields()
  }
  editForm.categoryId = null
  editForm.categoryName = ''
}

// 删除分类
const handleDelete = (row) => {  
  ElMessageBox.confirm(  
    `你确定要删除类别 "${row.categoryName}" 吗?`,  
    '警告',  
    {  
      confirmButtonText: '确定删除',  
      cancelButtonText: '取消',  
      type: 'warning',  
    }  
  )  
    .then(async () => {  
      try {
        const response = await request.delete(`/admin/categories/delete/${row.categoryId}`)
        
        if (response.data && response.data.code === 1) {
          ElMessage.success('删除成功')
          await fetchCategoryList() // 重新获取数据
        } else {
          ElMessage.error(response.data?.msg || '删除失败')
        }
      } catch (error) {
        console.error('删除分类失败:', error)
        if (error.response?.data?.msg) {
          ElMessage.error(error.response.data.msg)
        } else {
          ElMessage.error('网络错误，删除失败')
        }
      }
    })  
    .catch(() => {  
      ElMessage.info('已取消删除')
    })
}

// 组件挂载时获取数据
onMounted(() => {
  fetchCategoryList()
})
</script>  

<style scoped>  
.category-management {  
  padding: 20px;  
}  

.operation-container.el-card {  
  margin-bottom: 20px;  
}  

.el-form-item {  
  margin-bottom: 0;  
}  

.pagination-container {  
  display: flex;  
  justify-content: space-between;  
  align-items: center;  
  margin-top: 20px;  
}  

.ml-auto {  
  margin-left: auto;  
}

/* 表格样式优化 */
:deep(.el-table) {
  border-radius: 8px;
}

:deep(.el-table th) {
  background-color: #fafafa;
  color: #606266;
  font-weight: 600;
}

:deep(.el-table td) {
  padding: 12px 0;
}

/* 按钮样式 */
:deep(.el-button--primary) {
  transition: all 0.3s ease;
}

:deep(.el-button--primary:hover) {
  transform: translateY(-1px);
}

:deep(.el-button--warning) {
  transition: all 0.3s ease;
}

:deep(.el-button--warning:hover) {
  transform: translateY(-1px);
}

/* 卡片样式 */
:deep(.el-card) {
  border-radius: 10px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

/* 弹窗样式 */
:deep(.el-dialog) {
  border-radius: 12px;
}

/* 输入框样式 */
:deep(.el-input__wrapper) {
  border-radius: 6px;
  transition: all 0.3s ease;
}

:deep(.el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px #c0c4cc inset;
}

:deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 1px #409eff inset;
}

/* 分页样式 */
:deep(.el-pagination) {
  font-weight: 500;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .category-management {
    padding: 10px;
  }
  
  :deep(.el-col) {
    margin-bottom: 10px;
  }
  
  .pagination-container {
    flex-direction: column;
    gap: 10px;
  }
  
  .ml-auto {
    margin-left: 0;
  }
}
</style>
